package com.company.netty2;

import com.company.monitor.B;
import com.company.serialization.Student;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.stream.ChunkedFile;

import java.io.*;
import java.util.Collection;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
import static io.netty.handler.codec.http.HttpUtil.setContentLength;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @description: some desc
 * @author: ruoan
 * @date: 2021/1/1 23:44
 */
public class HttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

        Student ss = new Student();
        ss.setUserName("章SAN");
        ss.setUserId(11);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(ss);
        System.out.println(byteArrayOutputStream.toByteArray());
        /*if (!request.getDecoderResult().isSuccess()) {
            sendError(ctx, BAD_REQUEST);
            return;
        }
        if (request.getMethod() != GET) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }

        final String uri = request.getUri();
        final String path = sanitizeUri(uri);
        if (path == null) {
            sendError(ctx, FORBIDDEN);
            return;
        }
        File file = new File(path);
        if (file.isHidden() || !file.exists()) {
            sendError(ctx, NOT_FOUND);
            return;
        }

        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN);
            return;
        }

        RandomAccessFile randomAccessFile = null;

        randomAccessFile = new RandomAccessFile(file,"r");

        long fileLength = randomAccessFile.length();

        HttpResponse response = new DefaultHttpResponse(HTTP_1_1,OK);


        setContentLength(response,fileLength);

        setContentTypeHeader(response,file);

        if (isKeepAlive(request)) {
            response.headers().set(CONNECTION,KEEP_ALIVE);
        }

        ctx.write(response);
        ChannelFuture sendFileFuture;
        sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192)
                ,ctx.newProgressivePromise());

        sendFileFuture.addListener(new ChannelFutureListener() {
            
        })*/




    }


}
